package com.javaclimber.web20fundamentals.meetup.client;

import com.google.gwt.dom.client.Element;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Random;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;

public class MyHandler implements ClickHandler, KeyUpHandler {
	private Timer timer;
	private TextBox eventIdField;
	private TextBox apiKeyField;
	private DialogBox dialogBox;
	private MeetupServiceAsync meetupService;

	public MyHandler(TextBox eventIdField, TextBox apiKeyField,
			DialogBox dialogBox, MeetupServiceAsync meetupService) {

		this.eventIdField = eventIdField;
		this.apiKeyField = apiKeyField;
		this.dialogBox = dialogBox;
		this.meetupService = meetupService;
	}

	public void setTimer(Timer timer) {
		this.timer = timer;
	}

	/**
	 * Fired when the user clicks on the sendButton.
	 */
	public void onClick(ClickEvent event) {
		showMeetupUsers();
	}

	/**
	 * Fired when the user types in the nameField.
	 */
	public void onKeyUp(KeyUpEvent event) {
		if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
			showMeetupUsers();
		}
	}

	public void show2Members() {
		Element element = DOM.getElementById("numMembers");
		String sNumMembers = element.getInnerHTML();
		sNumMembers=sNumMembers.trim();
		int numMembers = Integer.parseInt(sNumMembers);

		int first = Random.nextInt(numMembers);

		int second = Random.nextInt(numMembers);

		if (first == second)
			second = Random.nextInt(numMembers);

		DOM.getElementById("first").setInnerHTML(
				DOM.getElementById("user" + first).getInnerHTML());

		DOM.getElementById("second").setInnerHTML(
				DOM.getElementById("user" + second).getInnerHTML());
	}

	/**
	 * Send the name from the nameField to the server and wait for a response.
	 */
	public void showMeetupUsers() {
		String eventId = eventIdField.getText().trim();
		String apiKey = apiKeyField.getText().trim();

		if ("".equals(eventId) || "".equals(apiKey)) {
			dialogBox.show();
			dialogBox.center();
			eventIdField.setFocus(true);
			eventIdField.selectAll();

			return;
		}

		RootPanel.get("home").setStyleName("noDisplay");

		final HTML loadingHTML = new HTML(
				"<font color='red'><b>Loading...</b></font>");
		RootPanel.get("networking").clear();
		RootPanel.get("networking").add(loadingHTML);
		RootPanel.get("networking").setStyleName("display");

		final int[] count = { 0 };
		final int[] callsFinished = { 0 };

		meetupService.lookupMeetupInfo(apiKey, eventId,
				new AsyncCallback<MeetupResponse>() {
					public void onFailure(Throwable caught) {
						Window.alert("ERROR: " + caught.getMessage());
					}

					public void onSuccess(MeetupResponse response) {
						final Result[] results = response.getResults();

						for (int i = 0; i < results.length; i++) {
							final Result result = results[i];

							meetupService.lookupProfile(results[i].getLink(),
									new AsyncCallback<Profile>() {
										public void onFailure(Throwable caught) {
											callsFinished[0]++;
											if (callsFinished[0] == results.length) {
												startSlideShow();
											}
										};

										public void onSuccess(Profile profile) {

											if (profile != null) {

												String user = "";
												user += "<div class='display' id='user"
														+ count[0] + "'>";

												count[0]++;
												user += "<table><tr><td valign='top'>";
												user += "<img src='"
														+ profile.getImage()
														+ "'/>";
												user += "</td><td width='20px'><td valign='top'>"
														+ "<h2>"
														+ result.getName()
														+ "</h2>"
														+ "<b>BIO:</b><br/>";
												user += profile.getBio();
												user += "<br/><br/><b>COMMENTS:</b><br/>";
												user += result.getComment();
												user += "<br/></td></tr></table>"
														+ "</div>\n";

												HTML html = new HTML(user);

												RootPanel.get("networking")
														.add(html);
											}
											callsFinished[0]++;
											if (callsFinished[0] == results.length) {
												startSlideShow();
											} else {
												loadingHTML
														.setHTML("<font color='red'><b>Loading...</b>"
																+ callsFinished[0]
																+ " of "
																+ results.length
																+ " completed</font>");
											}

										};

										private void startSlideShow() {
											RootPanel.get("networking").remove(
													loadingHTML);

											HTML memberView = new HTML(
													"<table width='100%'><tr><td width='50%' id='first' valign='top'>&nbsp;</td><td width='50%' id='second' valign='top'>&nbsp;</td></tr></table>");
											RootPanel.get("networking").add(
													memberView);

											HTML mcount = new HTML(
													"<div class='noDisplay' id='numMembers'>"
															+ count[0]
															+ "</div>");
											RootPanel.get("networking").add(
													mcount);

											hideAll();

											show2Members();
											//Window.alert(timer.toString());
											timer.scheduleRepeating(10000);

										}

										public void hideAll() {
											for (int i = 0; i < count[0]; i++) {
												DOM.getElementById("user" + i)
														.setClassName(
																"noDisplay");
											}

										}

									});

						}

					}
				});
	}
}
